package com.nuan.shiro.config;



import com.nuan.shiro.constants.CodeEnum;
import com.nuan.shiro.constants.Result;
import com.nuan.shiro.constants.ResultUtil;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 */
@RestControllerAdvice(basePackages = "com.nuan.shiro")
@Order(1)
public class GlobalExceptionControllerAdvice
{

    private static final Logger ERRORLOGGER = LoggerFactory.getLogger("errorLog");

    @ExceptionHandler(RuntimeException.class)
    public Result<?> unDefinedExceptionHandler(RuntimeException e){
        ERRORLOGGER.error("请求抛出异常", e);
        return ResultUtil.error(CodeEnum.SYSTEM_ERROR);
    }

    @ExceptionHandler(AuthorizationException.class)
    public Result<?> authorizationException(AuthorizationException e){
        ERRORLOGGER.error("请求抛出异常", e);
        return ResultUtil.error(CodeEnum.AUTH_FAIL);
    }

    @ExceptionHandler(UnauthorizedException.class)
    public Result<?> unauthorizedException(UnauthorizedException e){
        ERRORLOGGER.error("请求抛出异常", e);
        return ResultUtil.error(CodeEnum.AUTH_FAIL);
    }

    @ExceptionHandler(value = Exception.class)
    public Result<?> exceptionHandler(Exception e){
        // 其余异常简单返回为服务器异常
        ERRORLOGGER.error("Uncapped exception:",e);
        return ResultUtil.error(CodeEnum.SYSTEM_ERROR);
    }

}